<template>
    <div style="background-color: #f0f2f5; padding: 10px">
        <el-button @click="submitForm(ruleFormRef)">修改</el-button>
        <!-- <el-button type="danger">bao</el-button>
        <el-button type="success">修改</el-button>
        <el-button>刷新</el-button> -->
    </div>
    <br/>
    <!-- 采购申请添加 -->
     <h2 style="text-align: center;">采购申请</h2>
     <el-form
        ref="ruleFormRef"
        style="max-width: 1400px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
    >
    <p>基本信息</p>
    <!-- style="border-collapse: collapse;" -->
    <table>
        <tr>
            <td>
                <el-form-item label="单据主题：" prop="paApplyMotif">
                    <el-input v-model="ruleForm.paApplyMotif" />
                </el-form-item>
            </td>
            &nbsp;&nbsp;
            <td>
                <el-form-item label="单据编号：" prop="paNumber">
                    <el-input v-model="ruleForm.paNumber" disabled placeholder="保存后自动生成"/>
                </el-form-item>
            </td>
            &nbsp;&nbsp;
            <td>
                <el-form-item label="来源单据类型：" prop="paDocumentsType">
                    <el-select v-model="ruleForm.paDocumentsType" clearable placeholder="请选择来源单据类型">
                        <el-option label="无来源" value="无来源" />
                        <el-option label="销售合同" value="销售合同" />
                        <el-option label="生产订单" value="生产订单" />
                        <el-option label="采购定价" value="采购定价" />
                        <el-option label="项目档案" value="项目档案" />
                    </el-select>
                </el-form-item>
            </td>
            &nbsp;&nbsp;
            <td>
                <el-form-item label="来源单据：" prop="paDocuments">
                    <el-input v-model="ruleForm.paDocuments" />
                </el-form-item>
            </td>
        </tr>
        <tr>
            <td>
                <el-form-item label="采购申请类别：" prop="paApplicationType">
                    <el-select v-model="ruleForm.paApplicationType" clearable placeholder="请选择采购申请类别">
                        <el-option label="原材料采购" value="原材料采购" />
                        <el-option label="成品采购" value="成品采购" />
                        <el-option label="设备采购" value="设备采购" />
                    </el-select>
                </el-form-item>
            </td>
            &nbsp;&nbsp;
            <td>
                <el-form-item label="是否需要询价：" prop="isPAInquiry">
                    <el-radio-group v-model="ruleForm.isPAInquiry">
                        <el-radio :value="0">否</el-radio>
                        <el-radio :value="1">是</el-radio>
                    </el-radio-group>
                </el-form-item>
            </td>
            &nbsp;&nbsp;
            <td>
                <el-form-item label="制单日期：" prop="dates">
                    <el-date-picker
                        v-model="ruleForm.dates"
                        type="date"
                        placeholder="请选择制单日期"
                        format="YYYY/MM/DD"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
            </td>
            &nbsp;&nbsp;
            <td>
                <el-form-item label="制单人员：" prop="addName">
                    <el-input v-model="ruleForm.addName" />
                </el-form-item>
            </td>
        </tr>
        <tr>
            <td colspan="4"> 
                <el-form-item label="备注：" prop="efforts">
                    <el-input v-model="ruleForm.efforts" type="textarea" />
                </el-form-item>
            </td>
        </tr>
    </table>
    
    

    

    </el-form>

    <br/>

    <!-- 产品表格 -->
    <div>
        采购申请明细
        <el-button @click="addhang()" size="small">新增行</el-button>
    </div>
    <br/>
    <table border="1" style="border-collapse: collapse; width: 100%; height: 40px;">
        <thead>
            <tr>
                <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll" style="width: 30px;" /></th>
                <th style="height: 40px;">序号</th>
                <th>产品名称</th>
                <th>产品编号</th>
                <th>规格型号</th>
                <th>单位</th>
                <th>建议供应商</th>
                <th>数量</th>
                <th>单价</th>
                <th>需用日期</th>
                <th>备注</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="(item, index) in check1" :key="index">
                <td><input type="checkbox" v-model="ids" style="width: 30px;width: 100%;" @click="huoqu" /></td>
                <td style=" text-align: center;">{{ index + 1 }}</td>
                <td><input v-model="item.pName" type="text" style="height: 40px; width: 100%;text-align: center;"
                        @dblclick="dialogVisible3 = true" />
                </td>
                <td><input v-model="item.pNumber" type="text" style="height: 40px;width: 100%;text-align: center;"
                        :disabled="true" /></td>
                <td><input v-model="item.pSpec" type="text" style="height: 40px;width: 100%;text-align: center;"
                        :disabled="true" />
                </td>
                <td><input v-model="item.pUnit" type="text" style="height: 40px;width: 100%;text-align: center;"
                        :disabled="true" />
                </td>
                <td><input v-model="all.vname" type="text" style="height: 40px; width: 100%;text-align: center;"
                        @dblclick="dialogVisible2 = true" />
                </td>
                <td><input v-model="item.rPNum" type="text" style="height: 40px;width: 100%;text-align: center;"
                        @change="sumRPNum" /></td>
                <td><input v-model="item.rpPrice" type="text"
                        style="height: 40px;width: 100%;text-align: center;" />
                </td>
                <td>
                    <el-date-picker
                        v-model="item.dates"
                        type="date"
                        format="YYYY/MM/DD"
                        value-format="YYYY-MM-DD"
                    />
                </td>
                <td>
                    
                    <el-input
                        v-model="item.beizhu"
                        style="width: 240px"
                        :rows="2"
                        type="textarea"
                    />
                </td>
            </tr>
        </tbody>
    </table>

     <!-- 产品名称 -->
    <el-dialog v-model="dialogVisible3" title="产品名称选择" width="1000" style="height: 700px;">
        <span></span>
        <template #footer>
            <el-row>
                <el-col :span="4">
                    <el-tree style="max-width: 600px" :data="options" :props="defaultProps" @node-click="handleNodeClick" />
                </el-col>
                <el-col :span="20">
                    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange1">
                        <el-table-column type="selection" width="55" />
                        <el-table-column prop="pNumber" label="物品编码" align="center" width="140"/>
                        <el-table-column prop="pName" label="物品名称" align="center"/>
                        <el-table-column prop="pSpec" label="规格型号" align="center"/>
                        <el-table-column prop="pUnit" label="单位" align="center"/>
                    </el-table>
                </el-col>
            </el-row>
            <el-button type="primary" @click="dialogVisible3 = false">
                保存
            </el-button>
        </template>
    </el-dialog>

    <!-- 供应商弹出层 -->
    <el-dialog v-model="dialogVisible2" title="供应商选择" width="700" style="height: 700px;">
        <span></span>
        <template #footer>
            <el-table :data="tableDataven" border style="width: 100%" @selection-change="handleSelectionChanges">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" type="index" />
                <el-table-column prop="vName" label="供应商名称" />
                <el-table-column prop="vContact" label="联系人" />
                <el-table-column prop="vPhone" label="手机号码" />
            </el-table>
            <el-button type="success" @click="dialogVisible2 = false">确认</el-button>
        </template>
    </el-dialog>







</template>
    
<script setup lang='ts'>
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute,useRouter } from 'vue-router';
const route = useRoute()
const router = useRouter();
import http from '../../../http.js'

import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const locationOptions = ['Home', 'Company', 'School']

//随机数
const generateRandomNumber = () => {
    const a = Math.floor(100000 + Math.random() * 900000); // 生成一个 6 位的随机数
    // console.log(a);
    sessionStorage.setItem('paNumber', JSON.stringify(a));
}


onMounted(() => {
    generateRandomNumber(),//显示随机数
    GetProduct(),//产品列表
    getProducts(),//显示树形产品分类  
    table();//供应商列表
    // console.log()  
    // alert(route.query.id)  
    GetFan()//反填
})

//默认关闭产品弹框
const dialogVisible3 = ref(false)
//默认关闭供应商弹框
const dialogVisible2 = ref(false)
//采购申请表字段
const ruleForm = reactive({
    procureApplyId: '1',//采购申请id
    paNumber: '自动生成',//单据编号
    paDocumentsType: '',//来源单据类型
    paApplicationType: '',//采购申请类别
    isPAInquiry: 0,//是否需要询价通常用 0 表示不需要，1 表示需要
    paDocuments: '',//来源单据
    paApplyMotif: '',//单据主题
    paEnquiryState: 0,//询价状态
    paPurchaseState: 0,//采购状态
    paNumbers:'111',
    dates: '',//制单日期
    addName: localStorage.UserName,//添加人姓名
    addTime: '2024-12-19',//添加时间
    updName:'hhh',//修改人姓名
    updTime:'2024-12-19',//修改时间
    office_Id: '1',//公司id
    user_Id: 1,//用户id
    efforts:'',//备注
    list: [{
        purchaseproductId: '',//采购产品明细id
        paNumber: '',//采购申请id
        productId: '',//产品Id
        vendorId: '',//供应商id
        num: '',//数量
        price: '',//单价
        sumPrice: '',//总金额
        datess: '',//需用日期
        remark:''//备注
    }]
})


//反填
const GetFan=()=>{
    axios.get(http.zblnb+'/cg/api/ProcureApply/FanProcureApply?id='+route.query.id)
    .then(res=>{
         console.log(res)
        ruleForm.procureApplyId=res.data.data.procureApplyId
        ruleForm.paNumber=res.data.data.paNumber
        ruleForm.paDocumentsType=res.data.data.paDocumentsType
        ruleForm.paApplicationType=res.data.data.paApplicationType
        ruleForm.isPAInquiry=res.data.data.isPAInquiry
        ruleForm.paDocuments=res.data.data.paDocuments
        ruleForm.paApplyMotif=res.data.data.paApplyMotif
        ruleForm.paNumbers=res.data.data.paNumbers
        ruleForm.paEnquiryState=res.data.data.paEnquiryState
        ruleForm.paPurchaseState=res.data.data.paPurchaseState
        ruleForm.dates=res.data.data.dates
        ruleForm.addName=res.data.data.addName
        ruleForm.addTime=res.data.data.addTime
        ruleForm.office_Id=res.data.data.office_Id
        ruleForm.user_Id=res.data.data.user_Id
        ruleForm.efforts=res.data.data.efforts
        check1.value=res.data.data.list
        all.vname=res.data.data.list[0].vName
        // res.data.data.list.forEach(item=>{
        //     console.log(item)
        //     all.vname.item.vName
            // ruleForm.list.push({
            //    purchaseproductId: item.purchaseproductId,//采购产品明细id
            //     paNumber: item.paNumber,//采购申请id
            //     productId: item.productId,//产品Id
            //     vendorId: item.vendorId,//供应商id
            //     num: item.num,//数量
            //     price: item.price,//单价
            //     sumPrice:(Number(ele.rPNum)*Number(ele.rpPrice)),//总金额
            //     datess: item.datess,//需用日期
            //     remark:item.remark//备注
            // })
        // })
    })
    .catch(err=>{
        console.log(err)
    })
}




//c产品表字段
const formInline = reactive({
    PageIndex: 1,
    PageSize: 100,
    pageLast: 0,
    sumCount:0,
    PName: '',//产品名称
    PNumber: '',//产品编号
    Office_Id: '1',//公司id
    ProductTypeId:'',//产品类型id
})

//验证
const rules = reactive<FormRules>({
    paApplyMotif: [
        { required: true, message: '单据主题不能为空', trigger: 'blur' },
    ],
    dates: [
        { required: true, message: '制单日期不能为空', trigger: 'blur' },
    ],
})




//修改
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        // var model={
        //     procureApplyId:ruleForm.procureApplyId,//采购申请id
        //     paNumber:ruleForm.procureApplyId,//单据编号
        //     paDocumentsType:ruleForm.procureApplyId,//来源单据类型
        //     paApplicationType: ruleForm.procureApplyId,//采购申请类别
        //     isPAInquiry:ruleForm.procureApplyId,//是否需要询价通常用 0 表示不需要，1 表示需要
        //     paDocuments: ruleForm.procureApplyId,//来源单据
        //     paApplyMotif: ruleForm.procureApplyId,//单据主题
        //     paEnquiryState: ruleForm.procureApplyId,//询价状态
        //     paPurchaseState: ruleForm.procureApplyId,//采购状态
        //     dates: ruleForm.procureApplyId,//制单日期
        //     addName: ruleForm.procureApplyId,//添加人姓名
        //     addTime:ruleForm.procureApplyId,//添加时间
        //     updName:ruleForm.procureApplyId,//修改人姓名
        //     updTime:ruleForm.procureApplyId,//修改时间
        //     office_Id: ruleForm.procureApplyId,//公司id
        //     user_Id: ruleForm.procureApplyId,//用户id
        //     efforts:ruleForm.procureApplyId,//备注
        //     list:check1.value.map(item=>{
        //         purchaseproductId: item.purchaseproductId,//采购产品明细id
        //         paNumber:item.paNumber,//采购申请id
        //         productId:item.productId,//产品Id
        //         vendorId:item.purchaseproductId,//供应商id
        //         num: item.purchaseproductId,//数量
        //         price: item.purchaseproductId,//单价
        //         sumPrice: item.purchaseproductId,//总金额
        //         datess: item.purchaseproductId,//需用日期
        //         remark:item.purchaseproductId//备注
        //     })
        // }
        check1.value.forEach(ele => {
            ruleForm.list.push({
               purchaseproductId: '11',//采购产品明细id
                paNumber: '1111',//采购申请id
                productId: ele.productId,//产品Id
                vendorId: all.vendorId,//供应商id
                num: ele.rPNum,//数量
                price: ele.rpPrice,//单价
                sumPrice:(Number(ele.rPNum)*Number(ele.rpPrice)),//总金额
                datess: ele.dates,//需用日期
                remark:ele.beizhu//备注
            })
        })
        ruleForm.list = ruleForm.list.filter((item) => item.paNumber != '')
        console.log(ruleForm)
        axios.post(http.zblnb+'/cg/api/ProcureApply/UpdProcureApply',ruleForm)
        .then(res => {
            if (res.data.data > 0) {
                ElMessage.success('修改成功')
                router.push('/ShowProcureApply')
            }
            else if (res.data.data == -1) {
                ElMessage.error('该主题名称已重复，不可修改');
                return
            }
            else {
                ElMessage.error('修改失败')
                return
            }
        })
        .catch(err => {
            console.log(err)    
        })
        
    } else {
      console.log('error submit!', fields)
    }
  })
}

//点击新增行
const addhang = () => {
    check1.value.push({
        pName: '',//产品名称
        pNumber: '',//产品编号
        pSpec:'',//产品规格
        pUnit: '',//单位,
        rPNum: '',//数量
        rpPrice: '',//单价
        dates: '',
        beizhu:'',//备注
    });
}

const options = ref([]);
//选择左侧产品分类
const defaultProps = {
    children: 'children',
    label: 'label',
}
const getProducts = () => {
    axios.get(http.zblnb+"/erpcp/api/ProductType/ProductTypeSelect")
    .then(res => {
        options.value = res.data.data;
    })
    .catch(err => {
        console.log(err);
    })
}
//点击产品分类获取id
const handleNodeClick = (data: any) => {
    // console.log(data.value);
    formInline.ProductTypeId = data.value;
}

//产品弹框里的多选框
const check1 = ref([])//获取选择的产品数据
const handleSelectionChange1 = (val:any) => {
    check1.value = val
    console.log(check1.value)
}

//获取产品列表
const tableData=ref([])
const GetProduct = () => {
    axios.get(http.zblnb+'/erpcp/api/Product/ProductShow', {
        params: {
            PageIndex: formInline.PageIndex,
            PageSize: formInline.PageSize,
            PName: formInline.PName,
            PNumber: formInline.PNumber,
            Office_Id: formInline.Office_Id,
            ProductTypeId:formInline.ProductTypeId ||0 
        }
    })
    .then(res => {
        // console.log(res)
        tableData.value = res.data.data.list
        formInline.pageLast = res.data.data.pageLast
        formInline.sumCount = res.data.data.sumCount
    })
    .catch(err => {
        console.log(err)    
    })
}

//全选
const ids = ref([])
const selectAll = ref(false)
const toggleSelectAll = () => {
    ids.value = []
    if (selectAll.value) {
        ids.value = check1.value
    }else {
        ids.value = []
    }
    console.log(ids.value)
}

//点击复选框获取选中的值
const selectedRows = ref([])
const huoqu = () => {
    if (ids.value.length > 0) {
        selectedRows.value = check1.value;
        console.log(selectedRows.value)
    } else {
         selectedRows.value = []
          
    }
    
}

//供应商显示
var tableDataven = ref([]);
const table = () => {
    axios.get(http.zblnb + '/cg/api/Vendor/ProductTypeSelectShow', {
        params: {
            PageIndex: 1,
            PageSize: 100
        }
    }).then(res => {
        if (res.data.code == 200) {
            tableDataven.value = res.data.data.list
        }
        // console.log(tableDataven.value)
    })
}

//供应商多选框
const all = reactive({
    vname: '',
    vendorId:''
})
const handleSelectionChanges = (val: any) => {
    all.vname = val[0].vName;
    all.vendorId = val[0].vendorId;
};


// //输入数量change事件
// const sumRPNum = (sum: number) => {
//     console.log(sum)
//     // form.prTotalQuantity += Number(sum.srcElement.__vnode.dirs[0].value);
//     // console.log(form.prTotalQuantity)
// }

// //输入金额change事件
// const sumRPPrice = (sum: number) => {
//     console.log(sum)
//     form.pRtotalAmount += Number(sum.srcElement.__vnode.dirs[0].value);
//     console.log(form.pRtotalAmount)
// }









    
</script>
    
<style>
    
</style>